<template>
    <pageTabelLayout>
        <template #pageHeader>
            <div class="search-form divClass" v-if="headerShow">
                <div>
                    <a-form :model="queryData" size="small" layout="inline">
                        <a-form-item label="流转卡号" :style="{ width: '270px' }" label-col-flex="80px">
                            <a-input allow-clear class="bacClass" placeholder="请扫流转卡号二维码" v-model="pageData.circulatCard"
                                ref="getFocus1" @press-enter="huiche" @change="changeLz(pageData.circulatCard)" />
                        </a-form-item>
                        <!-- <a-form-item label="记录单号" :style="{ width: '270px' }" label-col-flex="70px">
                            <a-input allow-clear class="bacClass" placeholder="" v-model="pageData.recordCode"
                                @press-enter="huiche" />
                        </a-form-item> -->
                        <a-form-item label="编制日期" :style="{ width: '270px' }" label-col-flex="80px">
                            <a-date-picker  popup-container="html"  allow-clear class="bacClass" placeholder="" v-model="pageData.orgDate"
                                @press-enter="huiche" />
                        </a-form-item>
                        <a-form-item label="布号" :style="{ width: '270px' }" label-col-flex="80px">
                            <a-input allow-clear class="bacClass" placeholder="" v-model="pageData.clothCode"
                                @press-enter="huiche" />
                        </a-form-item>
                        <a-form-item label="客户名称" :style="{ width: '270px' }" label-col-flex="80px">
                            <a-input allow-clear class="bacClass" placeholder="" v-model="pageData.customName"
                                @press-enter="huiche" />
                        </a-form-item>
                        <a-form-item label="计划单号" :style="{ width: '270px' }" label-col-flex="80px">
                            <a-input allow-clear class="bacClass" placeholder="" v-model="pageData.planCode"
                                @press-enter="huiche" />
                        </a-form-item>
                        <a-form-item label="品名" :style="{ width: '270px' }" label-col-flex="80px">
                            <a-input allow-clear class="bacClass" placeholder="" v-model="pageData.brandName"
                                @press-enter="huiche" />
                        </a-form-item>
                        <a-form-item label="作业性质" :style="{ width: '270px' }" label-col-flex="80px">
                            <a-input allow-clear class="bacClass" placeholder="" v-model="pageData.nature"
                                @press-enter="huiche" />
                        </a-form-item>
                        <a-form-item label="色号" :style="{ width: '270px' }" label-col-flex="80px">
                            <a-input allow-clear class="bacClass" placeholder="" v-model="pageData.colorCode"
                                @press-enter="huiche" />
                        </a-form-item>
                        <a-form-item label="色称" :style="{ width: '270px' }" label-col-flex="80px">
                            <a-input allow-clear class="bacClass" placeholder="" v-model="pageData.colorName"
                                @press-enter="huiche" />
                        </a-form-item>
                        <a-form-item label="审核状态" :style="{ width: '270px' }" label-col-flex="80px">
                            <a-select popup-container="html"  allow-clear class="bacClass" placeholder="" v-model="pageData.auditState"
                                @press-enter="huiche">
                                <a-option :value="0">未审核</a-option>
                                <a-option :value="1">已审核</a-option>
                                <a-option :value="2">审核驳回</a-option>
                            </a-select>
                        </a-form-item>
                    </a-form>
                </div>

            </div>
            <div class="my-divisders">
                <a-divider orientation="center">
                    <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
                    <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
                </a-divider>
            </div>
            <div class="my-tool-bar">
                <Toolbar :style="{ width: '629px !important' }" :items="['查询', '新增', '删除', '审核', '驳回', '导出', '打印']" @select="cx"
                    @add="addTz" @dyBoufei="printTz" @export="exportExcel" @del="deleteHandler" @audit="audit"
                    @rejected="rejected">
                </Toolbar>
            </div>
        </template>
        <template #pageTabel>
            <!-- <a-tabs   default-active-key="1">
                <a-tab-pane key="1" title="未处理"> -->
            <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" :localeText="localeText1"
                rowSelection="multiple" @grid-ready="gridReady" style="height:100%" :defaultColDef="defaultColDef"
                class='ag-theme-alpine' :rowData="table.dataList" :columnDefs="tc">
            </AgGridVuesCopys>
            <!-- </a-tab-pane> -->
            <!-- <a-tab-pane key="2" title="已处理">
                      <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" :localeText="localeText1" rowSelection="multiple" @grid-ready="gridReady" style="height:100%"
                        :defaultColDef="defaultColDef" class='ag-theme-alpine' :rowData="table.dataList" :columnDefs="tc">
                    </AgGridVuesCopys>
                </a-tab-pane>
            </a-tabs> -->
        </template>
        <paginationCopys :total="total" show-total show-jumper show-page-size @change="PageSize" @page-size-change="change1"
            style="justify-content: center" :page-size="pagination.pageSize" :current="pagination.page" />
        <a-drawer ok-text='保存' cancel-text='关闭' :style="{ zIndex: 999 }" height="95%" :mask-closable="false"
            popup-container=".arco-tabs-content" placement="bottom" :visible="pageData.showAdd" unmountOnClose @ok="sideOk"
            @cancel="sideNo">
            <template #title>
                {{ pageData.sideTitle }}
            </template>
            <a-form :model="querDatas" size="mini" layout="inline" ref="formRef">
                <a-form-item label="配方单号" :style="{ width: '290px' }" label-col-flex="90px">
                    <a-input class="bacClass" allow-clear placeholder="" v-model="queryData.formulaCode" disabled />
                </a-form-item>
                <a-form-item label="设备编号" :style="{ width: '290px' }" label-col-flex="90px">
                    <a-select popup-container="html"  allow-clear :class="{ 'bacClass': !pageData.isDetails }" placeholder=""
                        v-model="queryData.equipmentNo" :disabled="pageData.isDetails" @focus="focusSb">
                        <a-option v-for="(item, index) in pageData.equipmentNo" :value="item['controlMachineCode']">{{
                            item['controlMachineCode'] }}</a-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="编制日期" :style="{ width: '290px' }" label-col-flex="90px">
                    <a-date-picker  popup-container="html"  allow-clear :class="{ 'bacClass': !pageData.isDetails }" placeholder=""
                        v-model="queryData.orgDate" :disabled="pageData.isDetails" />
                </a-form-item>
                <a-form-item label="性质" :style="{ width: '290px' }" label-col-flex="90px">
                    <a-select popup-container="html"  allow-clear :class="{ 'bacClass': !pageData.isDetails }" placeholder="" allow-search
                        v-model="queryData.nature" :disabled="pageData.isDetails" @search="getProperty"
                        @focus="getProperty('')">
                        <a-option v-for="(item, index) in pageData.property" :value="item['property']">{{
                            item['property'] }}</a-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="计划单号:" :style="{ width: '290px' }" label-col-flex="90px">
                    <a-input class="bacClass" allow-clear placeholder="" v-model="queryData.planCode" disabled />
                </a-form-item>
                <a-form-item label="客户名称:" :style="{ width: '290px' }" label-col-flex="90px">
                    <a-input class="bacClass" allow-clear placeholder="" v-model="queryData.customName" disabled />
                </a-form-item>
                <a-form-item label="流转卡号" :style="{ width: '290px' }" label-col-flex="90px">
                    <!-- <a-select popup-container="html"  allow-clear :class="{ 'bacClass': !pageData.isDetails }" placeholder=""
                        v-model="queryData.circulatCard" :disabled="pageData.isDetails" @focus="focusLz"
                        @change="changeCode(queryData.circulatCard)">
                        <a-option v-for="(item, index) in pageData.circulatCardList" :value="item['flowCardCode']">{{
                            item['flowCardCode'] }}</a-option>
                    </a-select> -->
                    <a-input allow-clear placeholder="" v-model="queryData.circulatCard" class="bacClass"
                        @press-enter="changeCode(queryData.circulatCard)" />
                </a-form-item>
                <a-form-item label="布号:" :style="{ width: '290px' }" label-col-flex="90px">
                    <a-input class="bacClass" allow-clear placeholder="" v-model="queryData.clothCode" disabled />
                </a-form-item>
                <a-form-item label="品名:" :style="{ width: '290px' }" label-col-flex="90px">
                    <a-input class="bacClass" allow-clear placeholder="" v-model="queryData.brandName" disabled />
                </a-form-item>
                <a-form-item label="色称:" :style="{ width: '290px' }" label-col-flex="90px">
                    <a-input class="bacClass" allow-clear placeholder="" v-model="queryData.colorName" disabled />
                </a-form-item>
                <a-form-item label="色号:" :style="{ width: '290px' }" label-col-flex="90px">
                    <a-input class="bacClass" allow-clear placeholder="" v-model="queryData.colorCode" disabled />
                </a-form-item>
                <a-form-item label="颜色深浅:" :style="{ width: '290px' }" label-col-flex="90px">
                    <a-select popup-container="html"  allow-clear :class="{ 'bacClass': !pageData.isDetails }" placeholder="" allow-search
                        v-model="queryData.colorDepth" :disabled="pageData.isDetails" @search="getColorDepth"
                        @focus="getColorDepth('')">
                        <a-option v-for="(item, index) in pageData.colorDepth" :value="item['colorDepth']">{{
                            item['colorDepth'] }}</a-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="水比:" :style="{ width: '290px' }" label-col-flex="90px">
                    <a-input-number allow-clear placeholder="" v-model="queryData.waterRate" class="input-demo bacClass"
                        :min="0" :max="1000000000000" :precision="2" @change="cahngeSb" />
                </a-form-item>
                <a-form-item label="匹数:" :style="{ width: '290px' }" label-col-flex="90px">
                    <a-input-number class="input-demo bacClass" allow-clear placeholder="" v-model="queryData.pieceNum" />
                </a-form-item>
                <a-form-item label="重量:" :style="{ width: '290px' }" label-col-flex="90px">
                    <a-input-number class="input-demo bacClass" allow-clear placeholder="" v-model="queryData.weight"
                        @change="cahngeSb" />
                </a-form-item>
                <a-form-item label="工序:" :style="{ width: '290px' }" label-col-flex="90px">
                    <a-select popup-container="html"  allow-clear :class="{ 'bacClass': !pageData.isDetails }" placeholder="" allow-search
                        v-model="queryData.process" :disabled="pageData.isDetails" @search="getProcess"
                        @focus="getProcess('')">
                        <a-option v-for="(item, index) in pageData.process" :value="item['processName']">{{
                            item['processName'] }}</a-option>
                    </a-select>
                </a-form-item>
                <!-- <a-form-item label="班组:" :style="{ width: '290px' }" label-col-flex="90px">
                    <a-input allow-clear placeholder="" v-model="queryData.team" />
                </a-form-item> -->
                <a-form-item label="拼缸缸号:" :style="{ width: '290px' }" label-col-flex="90px">
                    <a-input class="bacClass" allow-clear placeholder="" v-model="queryData.spellCylinderNo" disabled />
                </a-form-item>
                <a-form-item label="备注:" :style="{ width: '100%' }" label-col-flex="90px">
                    <a-textarea placeholder="" v-model="queryData.remark" :max-length="400" allow-clear
                        :class="{ 'bacClass': !pageData.isDetails }" show-word-limit />
                </a-form-item>
            </a-form>

            <a-space style="margin-bottom: 10px" v-if="!pageData.isDetails">
                <a-button type="primary" @click="addLine" size="mini">新增</a-button>
                <a-button type="primary" @click="delLine" size="mini">删除</a-button>
            </a-space>

            <a-table size="mini" :scrollbar="true" sticky-header stripe
                :row-selection="{ showCheckedAll: true, width: 50, onlyCurrent: true }"
                v-model:selected-keys="selectedRowKeys1" row-key="id" :bordered="{ cell: true }" :pagination="false"
                :columns="tableColumns2" :data="queryData.FormulaMarkDetail">
                <template #processName="{ record }">
                    <div style="width: 100%">
                        <a-select popup-container="html"  class="bacClass" v-model="record.processName" @focus="getProcessName">
                            <a-option v-for="(item, index) in pageData.processName" :value="item['processName']">{{
                                item['processName'] }}</a-option>
                        </a-select>
                    </div>
                </template>
                <template #programNo="{ record }">
                    <div style="width: 100%">
                        <a-select popup-container="html"  class="bacClass" v-model="record.programNo" @focus="getProgramNumber(1)"
                            @change="changePn(record.programNo, record)">
                            <a-option v-for="(item, index) in pageData.programNumber" :value="item['programNumber']">{{
                                item['programNumber'] }}</a-option>
                        </a-select>
                    </div>
                </template>
                <template #programName="{ record }">
                    <div style="width: 100%">
                        <a-select popup-container="html"  class="bacClass" v-model="record.programName" @focus="getProgramNumber(2)"
                            @change="changePn1(record.programName, record)">
                            <a-option v-for="(item, index) in pageData.programName" :value="item['programName']">{{
                                item['programName'] }}</a-option>
                        </a-select>
                    </div>
                </template>
                <template #adjuvantCode="{ record }">
                    <div style="width: 100%">
                        <a-select popup-container="html"  class="bacClass" v-model="record.adjuvantCode" @focus="getStereotypeAdjuvant(1)"
                            @change="changeAc(record.adjuvantCode, record)">
                            <a-option v-for="(item, index) in pageData.adjuvantCode" :value="item['adjuvantCode']">{{
                                item['adjuvantCode'] }}</a-option>
                        </a-select>
                    </div>
                </template>
                <template #adjuvantName="{ record }">
                    <div style="width: 100%">
                        <a-select popup-container="html"  class="bacClass" v-model="record.adjuvantName" @focus="getStereotypeAdjuvant(2)"
                            @change="changeAn(record.adjuvantName, record)">
                            <a-option v-for="(item, index) in pageData.adjuvantName" :value="item['adjuvantName']">{{
                                item['adjuvantName'] }}</a-option>
                        </a-select>
                    </div>
                </template>
                <template #rawmaterialType="{ record }">
                    <div style="width: 100%">
                        <a-input class="bacClass" v-model="record.rawmaterialType" />
                    </div>
                </template>
                <template #concentration="{ record }">
                    <div style="width: 100%">
                        <a-input-number v-model="record.concentration" class="input-demo bacClass" :min="0" :max="100"
                            @change="changeNd(record, record.concentration)" />
                    </div>
                </template>

                <template #unit="{ record }">
                    <div style="width: 100%">
                        <a-select popup-container="html"  class="bacClass" v-model="record.unit" @focus="focusunit1" allow-clear>
                            <a-option v-for="item in pageData.UnitList" :value="item['detailNameEn']">{{
                                item["detailNameEn"] }}
                            </a-option>
                        </a-select>
                    </div>
                </template>
                <template #remark="{ record }">
                    <div style="width: 100%">
                        <a-input class="bacClass" v-model="record.remark" />
                    </div>
                </template>
            </a-table>

        </a-drawer>
        <a-modal draggable :visible="visible" @ok="handleOk" @cancel="handleCancel" okText="打印" cancelText="关闭"
            unmountOnClose :width="1200">
            <template #title>
                打印
            </template>
            <div id="pfd">
                <div style="width:100%;position: relative;">
                    <h3 style="margin: 0 auto;width: 100%;text-align: center;">肇庆市粤隆纺织有限公司</h3>
                    <h2 style="margin: 10 auto;width: 100%;text-align: center;">整理配方单</h2>
                    <div style="position: absolute;top: 0px ;right: 380px;">
                        <QrcodeVue :value="queryData['formulaCode']"></QrcodeVue>
                    </div>
                    <div><span>配方单号：{{ queryData['formulaCode'] }}</span><span style="margin: 0 100px;">开单日期：{{
                        queryData['orgDate'] }}</span><span>机台号：{{ queryData['orgDate'] }}</span></div>
                    <table style="border-collapse:collapse;width:100%;" class="table">
                        <tr>
                            <td>流转卡号</td>
                            <td>{{ queryData['circulatCard'] }}</td>
                            <td>计划单号</td>
                            <td>{{ queryData['planCode'] }}</td>
                            <td>客户名称</td>
                            <td>{{ queryData['customName'] }}</td>
                            <td>工序</td>
                            <td>{{ queryData['process'] }}</td>
                        </tr>
                        <tr>
                            <td>布号</td>
                            <td>{{ queryData['clothCode'] }}</td>
                            <td>品名</td>
                            <td colspan="5">{{ queryData['brandName'] }}</td>
                        </tr>
                        <tr>
                            <td>色号</td>
                            <td>{{ queryData['colorCode'] }}</td>
                            <td>色称</td>
                            <td>{{ queryData['colorName'] }}</td>
                            <td>匹数</td>
                            <td>{{ queryData['pieceNum'] }}</td>
                            <td>重量</td>
                            <td>{{ queryData['weight'] }}</td>
                        </tr>
                        <tr>
                            <td>助剂编号</td>
                            <td colspan="2">助剂名称</td>
                            <td>浓度</td>
                            <td>浓度单位</td>
                            <td>水量</td>
                            <td>用料</td>
                            <td>单位</td>
                        </tr>
                        <tr v-for="(item, index) in queryData['FormulaMarkDetail']">
                            <td>{{ item['adjuvantCode'] }}</td>
                            <td colspan="2">{{ item['adjuvantName'] }}</td>
                            <td>{{ item['concentration'] }}</td>
                            <td>{{ item['concentrationUnit'] }}</td>
                            <td>{{ item['waterAmount'] }}</td>
                            <td>{{ item['materialAmount'] }}</td>
                            <td>{{ item['unit'] }}</td>
                        </tr>
                        <tr>
                            <td>备注</td>
                            <td colspan="7">{{ queryData['remark'] }}</td>
                        </tr>
                    </table>
                    <div><span>制单人：{{ queryData['createName'] }}</span><span
                            style="margin: 0 100px;">配方：</span><span>审核：</span><span style="margin-left: 100px;">称料：</span>
                    </div>
                </div>
            </div>
        </a-modal>
    </pageTabelLayout>
</template>
<script lang='ts' setup>
import { number } from 'echarts/core';
import { reactive, toRefs, ref } from 'vue'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table'
import { post } from '@/api/http'
import { url } from 'inspector';

import { Message, Modal } from '@arco-design/web-vue';
import { IconDoubleUp, IconDoubleDown } from '@arco-design/web-vue/es/icon';
import { localeText } from '@/api/aggridZw'
import printJS from 'print-js'
import { InputInstance } from "@arco-design/web-vue/es/input";
import { Key } from '@element-plus/icons-vue';
import QrcodeVue from 'qrcode.vue'
//引入导出方法
import { EXPORTEXEL, EXELTABLE } from '@/utils/exportEXCEL'
const localeText1: any = ref(localeText)

const queryData: any = reactive({
    "formulaCode": "",
    "orgDate": "",
    "equipmentNo": "",
    "nature": "",
    "planCode": "",
    "customName": "",
    "circulatCard": "",
    "clothCode": "",
    "brandName": "",
    "colorCode": "",
    "colorName": "",
    "colorDepth": "",
    "waterAmount": 0,
    "waterRate": 0,
    "pieceNum": 0,
    "weight": 0,
    "process": "",
    "team": "",
    "spellCylinderNo": "",
    "remark": "",
    FormulaMarkDetail: [],
});
const pageData: any = reactive({
    showAdd: false,
    sideTitle: '新增',
    circulatCardList: [],
    fabricId: null,
    id: null,
    dataList: [],
    circulatCard: "",
    orgDate: "",
    clothCode: "",
    customName: "",
    planCode: "",
    brandName: "",
    nature: "",
    colorCode: "",
    colorName: "",
    waterAmount: 0,
    totalMaterialAmount: 0,
    inputMaterialNum: 0,
    materialAmount: 0,
    totalWaterAmount: 0,
    concentration: 0,
    processName: [],
    adjuvantCode: [],
    adjuvantName: [],
    programNumber: [],
    programName: [],
    UnitList: [],
    equipmentNo: [],
    colorDepth: [],
    process: [],
    property: [],
    auditState: null
})
const getFocus1 = ref<InputInstance | null>(null);
onMounted(() => {
    getFocus1.value?.focus();
});


const querDatas = ref({})
const formRef = ref()
const sideOk = () => {
    formRef.value?.validate().then((err: any) => {
        if (!err) {
            for (let key in queryData) {
                // queryData['fabricId'] = pageData.fabricId
                if (key == 'FormulaMarkDetail') {
                    queryData[key].forEach(function (o: any) {
                        // o['fabricId'] = pageData.fabricId
                        if ((o['id'] + '').indexOf('add') != -1) {
                            o['id'] = null
                        }
                        o['fabricId'] = queryData['fabricId']
                        // o['fabricId'] = 1
                    })
                }
            }
            pageData.pageLoading = true;
            if (pageData.sideTitle === "新增") {
                post({
                    url: "/dwWorkShop/FormulaMark/insertList",
                    data: queryData
                }).then((res: any) => {
                    if (res.code === 200) {
                        formRef.value?.resetFields();
                        pageData.showAdd = false;
                        Message.success({
                            content: "保存成功",
                            duration: 5000,
                        });
                    } else {
                        Message.error({
                            content: res.message,
                            duration: 5000,
                        });
                    }
                    doRefresh();
                }).finally(() => {
                    pageData.pageLoading = false
                })
            } else if (pageData.sideTitle === "修改") {
                post({
                    url: "/dwWorkShop/FormulaMark/updateList",
                    data: queryData
                }).then((res: any) => {
                    if (res.code === 200) {
                        formRef.value?.resetFields();
                        pageData.showAdd = false;
                        Message.success({
                            content: "保存成功",
                            duration: 5000,
                        });
                    } else {
                        Message.error({
                            content: res.message,
                            duration: 5000,
                        });
                    }
                    doRefresh();
                }).finally(() => {
                    pageData.pageLoading = false
                })
            }
        }
    })
}

const sideNo = () => {
    pageData.showAdd = false
}

const addTz = () => {
    pageData.showAdd = true
    pageData.sideTitle = "新增"
    for (let key in queryData) {
        queryData[key] = ""
        if (key == "waterAmount" || key == "waterRate" || key == "pieceNum" || key == "weight") {
            queryData[key] = 0
        }
        if (key == 'FormulaMarkDetail') {
            queryData[key] = []
        }
    }
    getRecordCode()
}

const headerShow = ref<boolean>(true)
function doRefresh() {
    post({
        url: '/dwWorkShop/FormulaMark/getPage',
        data: {
            page: pagination.page,
            size: pagination.pageSize,
            circulatCard: pageData.circulatCard,
            orgDate: pageData.orgDate,
            clothCode: pageData.clothCode,
            customName: pageData.customName,
            planCode: pageData.planCode,
            brandName: pageData.brandName,
            nature: pageData.nature,
            colorCode: pageData.colorCode,
            colorName: pageData.colorName,
            auditState: pageData.auditState
        }
    }).then(({ data, code }: any) => {
        if (code === 200) {
            table.handleSuccess(data.list);
            // pagination.setTotalSize(data.total);
            gridOption.value.setRowData(data.list);
            total.value = data.total;
            pageData.dataList = data.list
        }
    })
        .catch(console.log);
}
const total = ref(0);
const page = ref(1);
const size = ref(0);
function PageSize(val: any) {
    pagination.page = val
    doRefresh();
}
function change1(val: any) {
    pagination.pageSize = val
    doRefresh();
}
const cx = () => {
    pagination.page = 1
    doRefresh()
}


const table = useTable()

const pagination = usePagination(doRefresh)
let selectedRowKeys1 = ref()
let selectedRowKeys2 = ref()

const tableColumns = useTableColumn([
    {
        title: "编制日期",
        key: "orgDate",
        dataIndex: "orgDate",
        width: 150,
    },

    {
        title: "配方单号",
        key: "formulaCode",
        dataIndex: "formulaCode",
        width: 150,
    },
    {
        title: "性质",
        key: "nature",
        dataIndex: "nature",
        width: 150,
    },
    {
        title: "设备编号",
        key: "equipmentNo",
        dataIndex: "equipmentNo",
        width: 120,
    },
    {
        title: "流转卡号",
        key: "circulatCard",
        dataIndex: "circulatCard",
        width: 150,
    },
    {
        title: "拼缸缸号",
        key: "spellCylinderNo",
        dataIndex: "spellCylinderNo",
        width: 150,
    },
    {
        title: "布号",
        key: "clothCode",
        dataIndex: "clothCode",
        width: 150,
    },
    {
        title: "品名",
        key: "brandName",
        dataIndex: "brandName",
        width: 150,
    },
    {
        title: "匹数",
        key: "pieceNum",
        dataIndex: "pieceNum",
        width: 150,
    },
    {
        title: "重量",
        key: "weight",
        dataIndex: "weight",
        width: 150,
    },
    {
        title: "工序",
        key: "process",
        dataIndex: "process",
        width: 150,
    },
    {
        title: "客户名称",
        key: "customName",
        dataIndex: "customName",
        width: 150,
    },
    {
        title: "计划单号",
        key: "planCode",
        dataIndex: "planCode",
        width: 150,
    },
    {
        title: "色号",
        key: "colorCode",
        dataIndex: "colorCode",
        width: 150,
    },
    {
        title: "色称",
        key: "colorName",
        dataIndex: "colorName",
        width: 150,
    },
    {
        title: "工艺卡号",
        key: "weight",
        dataIndex: "weight",
        width: 150,
    },
    {
        title: "创建人",
        key: "createName",
        dataIndex: "createName",
        width: 150,
    },
    {
        title: "创建时间",
        key: "createTime",
        dataIndex: "createTime",
        width: 150,
    },
    {
        title: "审核状态",
        key: "auditState",
        dataIndex: "auditState",
        slotName: 'auditState',
        width: 100,
        fixed: 'right'
    },
    {
        title: "操作",
        key: "act",
        dataIndex: "act",
        slotName: 'act',
        width: 150,
        fixed: 'right'
    }
])

let tc: any = tableColumns.map((o) => {

    let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed']
    }
    if (o.slotName === 'act') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj["lockPosition"] = "right"
        obj["width"] = 150
        obj['cellRenderer'] = {
            template: `<a-space><el-button style="color:#165dff;" link @click="a" v-if="(c==0||c==2)">修改</el-button>
            <el-button style="color:#165dff;" link @click="b">明细</el-button>
            </a-space>
            `,
            setup(props: any) {
                const a = () => {
                    editHandler(props.params.data)
                }
                const b = () => {
                    mxHandler(props.params.data)
                }
                return {
                    a,
                    b,
                    c: props.params.data.auditState

                }
            }

        }
    }
    if (o.slotName === 'auditState') {
        obj['resizable'] = false
        obj['filter'] = true
        obj['sortable'] = false
        obj["lockPosition"] = "right"
        obj["width"] = 100
        obj['cellRenderer'] = {
            template: `
            <el-tag class="ml-2" v-if="a == 0" type="warning">待审核</el-tag>
          <el-tag class="ml-2" v-if="a == 1" type="success">审核通过</el-tag>
          <el-tag class="ml-2" v-if="a == 2" type="info">审核驳回</el-tag>
          
            `,
            setup(props: any) {

                return {
                    a: props.params.data.auditState

                }
            }

        }
        obj['filterParams'] = {
            valueFormatter:(params)=>{
                return params.value == 0 ? '待审核' : params.value == 1 ? '审核通过' : params.value == 2 ? '审核驳回' : ''
            }
        }
    }

    return obj
})

let a = [{
    showRowGroup: 'hide_def',
    "headerName": "",
    "checkboxSelection": true,
    "headerCheckboxSelection": true,
    "pinned": "left",
    "width": 50,
    resizable: false,
    filter: false,
    sortable: false,
    minWidth: 50,
    maxWidth: 50,
    //lockPosition: "left",
}]
tc = a.concat(tc)

const dataList = ref('1')
// 表格准备事件
const gridOption = ref()
const gridReady = (params: any) => {
    gridOption.value = params.api
}
const defaultColDef = {
    sortable: true,
    resizable: true,
    filter: true,
    // flex: 1
}
const huiche = () => {
    doRefresh();
}
const editHandler = (record: any) => {
    pageData.sideTitle = '修改'
    pageData.showAdd = true

    pageData.fabricId = record['fabricId']
    pageData.id = record['id']
    cxFormulaMarkDetailList(record['id'])
    focusunit1()
    getProcessName()
    getStereotypeAdjuvant(1)
    getProgramNumber(1)
    getStereotypeAdjuvant(2)
    getProgramNumber(2)
    for (let key in record) {
        queryData[key] = record[key]
    }
}
const mxHandler = (record: any) => {
    pageData.isDetails = true
    pageData.sideTitle = '明细'
    pageData.showAdd = true
    for (let key in record) {
        queryData[key] = record[key]
    }
    pageData.fabricId = record['fabricId']
    pageData.id = record['id']
    cxFormulaMarkDetailList(record['id'])
    focusunit1()
    getProcessName()
    getStereotypeAdjuvant(1)
    getProgramNumber(1)
    getStereotypeAdjuvant(2)
    getProgramNumber(2)
}


const tableColumns2 = [
    {
        title: '工序名称',
        dataIndex: 'processName',
        slotName: 'processName',
        width: 150,
    },
    {
        title: '程序号',
        dataIndex: 'programNo',
        slotName: 'programNo',
        width: 150,
    },
    {
        title: '程序名称',
        dataIndex: 'programName',
        slotName: 'programName',
        width: 150,
    },
    {
        title: '助剂编号',
        dataIndex: 'adjuvantCode',
        slotName: 'adjuvantCode',
        width: 150,
    },
    {
        title: '助剂名称',
        dataIndex: 'adjuvantName',
        slotName: 'adjuvantName',
        width: 150,
    },
    {
        title: '原料类型',
        dataIndex: 'rawmaterialType',
        slotName: 'rawmaterialType',
        width: 150,
    },
    {
        title: '浓度',
        dataIndex: 'concentration',
        slotName: 'concentration',
        width: 150,
    },
    {
        title: '浓度单位',
        dataIndex: 'concentrationUnit',
        slotName: 'concentrationUnit',
        width: 150,
    },
    {
        title: '总水量',
        dataIndex: 'totalWaterAmount',
        slotName: 'totalWaterAmount',
        width: 150,
    },
    {
        title: '总用料',
        dataIndex: 'totalMaterialAmount',
        slotName: 'totalMaterialAmount',
        width: 150,
    },
    {
        title: '输料次数',
        dataIndex: 'inputMaterialNum',
        slotName: 'inputMaterialNum',
        width: 150,
    },
    {
        title: '用料(次)',
        dataIndex: 'materialAmount',
        slotName: 'materialAmount',
        width: 150,
    },
    {
        title: '水量(次)',
        dataIndex: 'waterAmount',
        slotName: 'waterAmount',
        width: 150,
    },
    {
        title: '单位',
        dataIndex: 'unit',
        slotName: 'unit',
        width: 150,
    },
    {
        title: '批号',
        dataIndex: 'batchNo',
        slotName: 'batchNo',
        width: 150,
    },
    {
        title: '备注',
        dataIndex: 'remark',
        slotName: 'remark',
        width: 150,
    },

]

//查询 弹窗根据 formulaMarkId查询表格数据
function cxFormulaMarkDetailList(id: any) {
    post({
        url: "dwWorkShop/FormulaMarkDetail/getList",
        data: { "formulaMarkId": id, }
    }).then(({ data, code }: any) => {
        if (code === 200) {
            queryData.FormulaMarkDetail = data
        } else {
            Message.error({
                content: "查询失败！",
                duration: 5000,
            });
        }
    });
}
let a1 = 0
const addLine = () => {
    if (queryData.waterRate == "" || queryData.waterRate == null || queryData.waterRate == undefined || queryData.weight == "" || queryData.weight == null || queryData.weight == undefined) {
        Message.error({
            content: '请先填写水比和重量！',
            duration: 5000,
        })
        return
    }
    //在这个数组前面添加一行
    queryData.FormulaMarkDetail.unshift({
        id: 'add' + a1++,
        "processName": "",
        "programNo": "",
        "programName": "",
        "adjuvantCode": "",
        "adjuvantName": "",
        "rawmaterialType": "",
        "concentration": 0,
        "concentrationUnit": "",
        "totalWaterAmount": parseFloat(pageData.totalWaterAmount),
        "totalMaterialAmount": 0,
        "inputMaterialNum": parseFloat(pageData.inputMaterialNum),
        "materialAmount": 0,
        "waterAmount": parseFloat(pageData.waterAmount),
        "unit": "",
        "batchNo": "",
        "remark": ""
    })


}
//成分 删除
const delLine = () => {

    if (selectedRowKeys1.value.length === 0) {
        Message.error({
            content: '请先勾选',
            duration: 5000,
        })
        return
    }
    queryData['FormulaMarkDetail'] = queryData['FormulaMarkDetail'].filter(function (o: any) {
        return selectedRowKeys1.value.indexOf(o['id']) === -1
    })

}

//打开打印弹窗
function printTz() {
    //判断是否勾选了数据
    // if (gridOption.value.getSelectedRows().length === 0) {
    //     Message.error('请勾选一条数据');
    //     return
    // }
    // if(gridOption.value.getSelectedRows().length>1){
    //     Message.error('请勾选一条数据');
    //     return
    // }
    // pageData.id=gridOption.value.getSelectedRows()[0]['id']
    // pageData.fabricId=gridOption.value.getSelectedRows()[0]['fabricId']
    visible.value = true;
}
const visible = ref(false);

const handleOk = () => {
    printJS({
        printable: 'pfd',
        type: 'html',
        targetStyles: ['*'],
    })
    visible.value = false;
};
const handleCancel = () => {
    visible.value = false;
}
//流转卡号改变
function changeLz(val: any) {
    post({
        url: "aps/circulatCard/getDropValue",
        data: { "circulatCard": val }
    }).then(({ data, code }: any) => {
        if (code === 200) {
            table.handleSuccess(data.list);
            gridOption.value.setRowData(data.list);
            total.value = data.total;
        } else {
            Message.error({
                content: "查询失败！",
                duration: 5000,
            });
        }
    });
}
//拿到所有流转卡号
function focusLz() {
    post({
        url: "aps/circulatCard/getDropValue",
        data: { flowCardCode: "" }
    }).then(({ data, code, message }: any) => {
        if (code === 200) {
            pageData.circulatCardList = data;
        } else {
            Message.error({
                content: message,
                duration: 5000,
            });
        }
    });
}
//新增修改 流转卡号改变
function changeCode(val: any) {
    post({
        url: "/dwWorkShop/FormulaMark/getCirculatCard",
        data: { circulatCard: val }
    }).then(({ data, code, message }: any) => {
        if (code === 200) {
            for (let key in queryData) {
                queryData[key] = ''
                if (key == "waterAmount" || key == "waterRate" || key == "pieceNum" || key == "weight") {
                    queryData[key] = 0
                }
                if (key == 'FormulaMarkDetail') {
                    queryData[key] = []
                }

            }
            for (let key in data[0]) {
                queryData[key] = data[0][key]
            }

        } else {
            Message.error({
                content: message,
                duration: 5000,
            });
        }
    });
}

// 导出
let exportExcel = () => {
    EXELTABLE(tableColumns, pageData.dataList, '整理配方制单')
}
//获取工序名称
function getProcessName() {
    post({
        url: "pdm/workprocedure/getFieldValue",
        data: { processName: "" }
    }).then(({ data, code, message }: any) => {
        if (code === 200) {
            pageData.processName = data

        } else {
            Message.error({
                content: message,
                duration: 5000,
            });
        }
    });
}
//获取定型助剂信息维护
function getStereotypeAdjuvant(num: any) {
    let ob = {}
    if (num == 1) {
        ob['adjuvantCode'] = ""
    } else {
        ob['adjuvantName'] = ""
    }
    post({
        url: "pdm/ProcessFormula/getSortList",
        data: ob
    }).then(({ data, code, message }: any) => {
        if (code === 200) {
            if (num == 1) {
                pageData.adjuvantCode = data
            } else {
                pageData.adjuvantName = data
            }

        } else {
            Message.error({
                content: message,
                duration: 5000,
            });
        }
    });
}
//获取程序号定义
function getProgramNumber(num: any) {
    let ob = {}
    if (num == 1) {
        ob['programNumber'] = ""
    } else {
        ob['programName'] = ""
    }
    post({
        url: "pdm/ProgramNumber/select",
        data: ob
    }).then(({ data, code, message }: any) => {
        if (code === 200) {
            if (num == 1) {
                pageData.programNumber = data
            } else {
                pageData.programName = data
            }

        } else {
            Message.error({
                content: message,
                duration: 5000,
            });
        }
    });
}
//程序号 改变
function changePn(val: any, record: any) {
    let list = pageData.programNumber.filter(function (o: any) {
        return o['programNumber'] == val
    })
    if (list.length > 0) {
        record['programName'] = list[0]['programName']
    }

}
//程序名 改变
function changePn1(val: any, record: any) {
    let list = pageData.programName.filter(function (o: any) {
        return o['programName'] == val
    })
    if (list.length > 0) {
        record['programNo'] = list[0]['programNumber']
    }
}
//助剂编号 改变
function changeAc(val: any, record: any) {
    let list = pageData.programNumber.filter(function (o: any) {
        return o['adjuvantCode'] == val
    })
    if (list.length > 0) {
        record['adjuvantName'] = list[0]['adjuvantName']
        record['concentrationUnit'] = list[0]['concentrationUnit']
        record['rawmaterialType'] = list[0]['rawmaterialType']
        record['unit'] = list[0]['unit']
    }

}
//助剂名称 改变
function changeAn(val: any, record: any) {
    let list = pageData.programName.filter(function (o: any) {
        return o['adjuvantName'] == val
    })
    if (list.length > 0) {
        record['adjuvantCode'] = list[0]['adjuvantCode']
        record['concentrationUnit'] = list[0]['concentrationUnit']
        record['rawmaterialType'] = list[0]['rawmaterialType']
        record['unit'] = list[0]['unit']
    }
}
//查询单价
function focusunit1() {
    post({
        url: 'dict/dictTypeDetail/getList',
        data: {
            codeType: 17,
            detailNameEn: ""
        }
    }).then(({ code, data }: any) => {
        if (code == 200) {
            pageData.UnitList = data;
        } else {
            Message.error({
                content: '查询失败',
                duration: 5000
            })
        }
    });
};
//查询设备编号
function focusSb() {
    post({
        url: 'pdm/controlMachine/getList',
        data: {

        }
    }).then(({ code, data }: any) => {
        if (code == 200) {
            pageData.equipmentNo = data;
        } else {
            Message.error({
                content: '查询失败',
                duration: 5000
            })
        }
    });
}
//重量 水比改变
function cahngeSb() {
    // waterAmount:0,
    // totalMaterialAmount:0,
    // inputMaterialNum:0,
    // materialAmount:0,
    // totalWaterAmount:0 concentration
    if (queryData.waterRate != null && queryData.waterRate != "" && queryData.weight != null && queryData.weight != "") {
        pageData.totalWaterAmount = parseFloat(queryData.waterRate) * parseFloat(queryData.weight)
    }
    // if(queryData.inputMaterialNum!=null&&queryData.inputMaterialNum!=""){
    //     pageData.inputMaterialNum=queryData.inputMaterialNum
    // }
    //当水量>1200 用料(次)=总用料/2,输料次数为2，水量/2
    if (parseFloat(queryData.waterAmount) >= 1200) {
        pageData.waterAmount = parseFloat(pageData.totalWaterAmount) / 2
        pageData.inputMaterialNum = 2
    } else {
        pageData.waterAmount = parseFloat(pageData.totalWaterAmount)
        pageData.inputMaterialNum = 1
    }
}
//浓度改变
function changeNd(record: any, val: any) {
    if (queryData.waterRate != null && queryData.waterRate != "" && queryData.weight != null && queryData.weight != "") {
        record.totalMaterialAmount = parseFloat(queryData.waterRate) * parseFloat(queryData.weight) * (parseFloat(val) / 100)
    }
    if (parseFloat(queryData.waterAmount) >= 1200) {
        record.materialAmount = parseFloat(record.totalMaterialAmount) / 2

    } else {
        record.materialAmount = parseFloat(record.totalMaterialAmount)
    }
}
//拿到单号
function getRecordCode() {
    post({
        url: 'dwWorkShop/FormulaMark/getCodeGenerate',
        data: {

        }
    }).then(({ code, data }: any) => {
        if (code == 200) {
            queryData.formulaCode = data;
        } else {
            Message.error({
                content: '查询失败',
                duration: 5000
            })
        }
    });

}
const deleteHandler = () => {
    if (gridOption.value.getSelectedRows().length === 0) {
        Message.error('请先勾选');
        return
    }

    Modal.confirm({
        title: '系统提示',
        content: '确认删除选中的数据?',
        onOk() {
            pageData.pageLoading = true;
            post({
                url: 'dwWorkShop/FormulaMark/delete',
                data: gridOption.value.getSelectedRows().map((o: any) => { return o.fabricId })
            }).then(({ code, data, message }: any) => {
                if (code === 200) {
                    Message.success({
                        content: '删除成功',
                        duration: 5000
                    })
                    pagination.page = 1
                    doRefresh()

                } else {
                    Message.error({
                        content: message,
                        duration: 5000
                    })
                }

            }).finally(() => {
                pageData.pageLoading = false
            });
        }
    })
}
//审核
function audit() {
    let rowList = gridOption.value.getSelectedRows()
    let flag = false
    rowList.forEach(function (o: any) {
        if (o['auditState'] == 1) {
            flag = true
        }
    })
    if (flag) {
        Message.warning({
            content: "勾选的数据存在审核通过的数据！请勿重复审核",
            duration: 5000
        })
    }
    AuditMethod(1)
}
//反审
function rejected() {
    let rowList = gridOption.value.getSelectedRows()
    let flag = false
    rowList.forEach(function (o: any) {
        if (o['auditState'] == 0 || o['auditState'] == 2) {
            flag = true
        }
    })
    if (flag) {
        Message.warning({
            content: "勾选的数据只能驳回审核过的数据！",
            duration: 5000
        })
    }
    AuditMethod(2)
}
//审核反审
function AuditMethod(num: any) {
    let rowList = gridOption.value.getSelectedRows().map((o: any) => { return { "id": o.fabricId, "auditState": num } })

    post({
        url: 'dwWorkShop/FormulaMark/setAudit',
        data: rowList
    }).then(({ code, data, message }: any) => {
        if (code == 200) {
            if (num == 1) {
                Message.success({
                    content: "审核成功！",
                    duration: 5000
                })
            } else {
                Message.success({
                    content: "驳回成功！",
                    duration: 5000
                })
            }
        } else {
            Message.error({
                content: message,
                duration: 5000
            })
        }
    });

}
//性质
function getProperty(val: any) {
    if (val || val == "") {
        post({
            url: 'pdm/formulaAttribute/getFieldValue',
            data: { "property": val }
        }).then(({ code, data }: any) => {
            if (code == 200) {
                pageData.property = data;
            } else {
                Message.error({
                    content: '查询失败',
                    duration: 5000
                })
            }
        });
    }

}

//颜色深浅
function getColorDepth(val: any) {
    if (val || val == "") {
        post({
            url: 'pdm/colorDepth/getFieldValue',
            data: { "colorDepth": val }
        }).then(({ code, data }: any) => {
            if (code == 200) {
                pageData.colorDepth = data;
            } else {
                Message.error({
                    content: '查询失败',
                    duration: 5000
                })
            }
        });
    }

}
//工序
function getProcess(val: any) {
    if (val || val == "") {
        post({
            url: 'pdm/workprocedure/getFieldValue',
            data: { "processName": val }
        }).then(({ code, data }: any) => {
            if (code == 200) {
                pageData.process = data;
            } else {
                Message.error({
                    content: '查询失败',
                    duration: 5000
                })
            }
        });
    }

}

</script>
<style lang='less' scoped>
.search-form {
    margin-top: 10px;
}

.fromTitle {
    width: 100%;
    background-color: white;
    padding: 0;
    box-sizing: border-box;
    display: flex;
    flex-direction: row;
    justify-content: space-between;

    form {
        width: 50% !important;
        margin-top: 10px !important;
    }

    &>.my-header {
        width: 100%;
        padding: 10px;
        padding-top: 0;
        background-color: white;


        min-height: 10%;

        &>.my-tool-bar {
            width: 100%;
            text-align: right;
            margin-top: 50px;
        }
    }
}

.fromTitle1 {
    margin-left: 50px;
    margin-top: 60px;
}

:deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.arco-space) {
    width: 410px !important;
}

.table tr,
.table td {
    border: 1px solid #3e3e3e;
    text-align: center;
}
</style>